Building APIs with Django and Django Rest Framework by Shabda Raaj

Building APIs with Django and Django Rest Framework by Shabda Raaj

Author:Shabda Raaj [Raaj, Shabda]
Language: eng
Format: epub
Publisher: Agiliq Info Solutions India Pvt Ltd
Published: 2018-07-28T23:00:00+00:00


Introducing Viewsets and Routers

Our urls are looking good, and we have a views with very little code duplication, but we can do better.

The /polls/ and /polls/<pk>/ urls require two view classes, with the same serializer and base queryset. We can group them into a viewset, and connect them to the urls using a router.

This is what it will look like:

# urls.py # ... from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('polls', PollViewSet, base_name='polls') urlpatterns = [ # ... ] urlpatterns += router.urls # views.py # ... from rest_framework import viewsets from .models import Poll, Choice from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer class PollViewSet(viewsets.ModelViewSet): queryset = Poll.objects.all() serializer_class = PollSerializer



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.